<?php

class BlogCategoryTable extends Doctrine_Table
{
  /**
   * Returns the Doctrine_Query object that fetches published categories.
   *
   * @param string $lang
   * @return Doctrine_Query
   */
  protected function getPublishedQuery($lang)
  {
    return $this->createQuery('a')->
      leftJoin('a.Translation t')->
      where('a.is_published = ?', true)->
      addWhere('t.lang = ?', $lang)
    ;
  }

  /**
   * Returns the Doctrine_Collection of published categories.
   *
   * @param string $lang
   * @return Doctrine_Collection
   */
  public function getPublishedCategories($lang = 'en')
  {
    return $this->getPublishedQuery($lang)->
      orderBy('t.name')->
      execute()
    ;
  }

  /**
   * Returns the BlogCategory table matching given criteria.
   *
   * @param array $parameters Request parameters
   * @return BlogCategory
   */
  public function retrieveActiveCategory(array $parameters)
  {
    $slug = sprintf('%s-%s', $parameters['sf_culture'], $parameters['category']);

    return $this->getPublishedQuery($parameters['sf_culture'])->
      addWhere('t.slug = ?', $slug)->
      fetchOne()
    ;
  }
  
  public function retrieveBackendList(Doctrine_Query $q)
  {
    $rootAlias = $q->getRootAlias();

    $q->leftJoin($rootAlias.'.Translation t');
    
    $q->orderBy('t.name asc');
    
    return $q;
  }
}
